<?php
defined('IN_IA') || exit('Access Denied');
class Asterye_waimaixiaModuleProcessor extends WeModuleProcessor
{
	protected $WeAccount;
	protected $MimiAccount;
	public function respond()
	{
		global $_W;
		$settings = $this->module['config'];
		$openid = $this->message["FromUserName"];
		$sessionfrom = $this->message["SessionFrom"];
		//$sessionfrom = str_replace("'",'"',$sessionfrom);	
		//$sessionfrom = json_decode($sessionfrom,true);
		
		if(!$sessionfrom){
			$actime = time()-300;
			$msgtype = pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_kefubind")." WHERE openid = '".$openid."' AND active_time >= ".$actime);
			$user = pdo_get($this->modulename . "_user", array("openid" => $openid, "uniacid" => $_W["uniacid"]));
			if($msgtype){
				$sessionfrom['type'] = $msgtype['type'];
				$sessionfrom['id'] = $msgtype['ad_id'];
			}else{
				//$text = "请点击右下角的快捷发送";
				//$resp = $this->respCustomText($text);
				//$res = $this->sendMiniCustom($resp);
			}
		
		
			if($sessionfrom['type'] == 'jd_goods' || $sessionfrom['type'] == 'tb_goods' || $sessionfrom['type'] == 'groupgoods'){
				if($msgtype){
					$msg = $msgtype;
				}else{
					$msg = pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_kefubind")." WHERE openid = '".$openid."'");
				}
				if($msg['type'] == 'jd_goods'){
					$msg['adtype'] = 5;
				}elseif($msg['type'] == 'tb_goods'){
					$msg['adtype'] = 3;
				}else{
					$msg['adtype'] = 2;
				}
				
			}

			if($sessionfrom['type'] == 'tb_feeds'){
				if($msgtype){
					$msg = $msgtype;
				}else{
					$msg = pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_kefubind")." WHERE openid = '".$openid."'");
				}
				$msg['adtype'] = 3;
			}
			
			if($sessionfrom['type'] == 'swiperad'){
				$msg = pdo_get($this->modulename . '_shopad',array('item_id'=>$sessionfrom['id']));
			}
			if($sessionfrom['type'] == 'tequan'){
				if($msgtype){
					$msg = $msgtype;
				}else{
					$msg = pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_kefubind")." WHERE openid = '".$openid."'");
				}
				$msg['adtype'] = 3;
			}
			if($sessionfrom['type'] == 'goods'){
				$msg = pdo_get($this->modulename . '_groupchat',array('id'=>$sessionfrom['id']));
				if($settings['huichat'] == 1){
					$msg['adtype'] = 3;
					$msg['link_title'] = $msg['goods_title'];
					$msg['link_desc'] = '点击购买';
					$msg['link_thumb'] = tomedia($msg['goods_img']);
					if($msg['goods_pintai'] == 'jd'){
						$msg['link_url'] = $settings['huidomain'].'/app/index.php?i='.$settings['huiuniacid'].'&c=entry&act=detail_'.$msg['goods_pintai'].'&do=qishishop&m=hc_card&skuId='.$msg['goods_id'].'&pid='.$settings['huiuserid'];
					}
					elseif($msg['goods_pintai'] == 'pdd'){
						$msg['link_url'] = $settings['huidomain'].'/app/index.php?i='.$settings['huiuniacid'].'&c=entry&act=detail'.$msg['goods_pintai'].'&do=qishishop&m=hc_card&skuId='.$msg['goods_id'].'&pid='.$settings['huiuserid'];
					}
					elseif($msg['goods_pintai'] == 'vip'){
						$msg['link_url'] = $settings['huidomain'].'/app/index.php?i='.$settings['huiuniacid'].'&c=entry&act=detailwph&do=qishishop&m=hc_card&skuId='.$msg['goods_id'].'&pid='.$settings['huiuserid'];
					}else{
						$msg['adtype'] = $msg['adtype'];
					}
				}
			}
			if($sessionfrom['type'] == 'shopad'){
				$msg = pdo_get($this->modulename . '_shop',array('shop_id'=>$sessionfrom['id']));
			}
			if($sessionfrom['type'] == 'ad'){
				$msg = pdo_get($this->modulename . '_ad',array('id'=>$sessionfrom['id']));
				
			}
			if($sessionfrom['type'] == 'ad_new'){
				$msg = pdo_get($this->modulename . '_ad_new',array('id'=>$sessionfrom['id']));
			}
			if($sessionfrom['type'] == 'hotel'){
				$msg = pdo_get($this->modulename . '_ad',array('id'=>$sessionfrom['id']));
				$msgurl = pdo_fetch("SELECT * FROM ".tablename($this->modulename . "_kefubind")." WHERE openid = '".$openid."'");
				$msg['link_url'] = $msgurl['link_url'];
				$msg['adtype'] = 3;
			}
			if($sessionfrom['type'] == 'shopenter'){
				$text = "请点击右下角的快捷发送";
				$resp = $this->respCustomText($text);
				$res = $this->sendMiniCustom($resp);
			}elseif($msg['adtype'] == 5){
				$text = $msg['content'];
				$resp = $this->respCustomText($text);
				$res = $this->sendMiniCustom($resp);
				sleep(1);
				$text = "👆 点击上面的链接购买/领券";
				$resp = $this->respCustomText($text);
				$res = $this->sendMiniCustom($resp);
			}elseif($msg['adtype'] == 2){
				$qrcode = str_replace("/addons/".$this->modulename, "", $_W["attachurl"]) . $msg['reply_thumb'];
				$folder = ATTACHMENT_ROOT . $this->modulename . "/temp/";
				if (!is_dir($folder)) {
					mkdir($folder, 511, true);
				}
				$filename = $folder . $_W["uniacid"] ."_". $openid . ".jpg";
				file_put_contents($filename, file_get_contents($qrcode));
				$media_id = $this->mediaUpload($_W["uniacid"], $filename);
				$resp = $this->respCustomImage($media_id);
				$res = $this->sendMiniCustom($resp);
				sleep(1);
				$text = $msg['reply_text'];
				$resp = $this->respCustomText($text);
				$res = $this->sendMiniCustom($resp);
			}elseif($msg['adtype'] == 3){
				$thumb = str_replace("/addons/".$this->modulename,"",tomedia($msg['link_thumb']));
				$resp = $this->respCustomLink($msg['link_title'],$msg['link_desc'],$msg['link_url'],$thumb);
				$res = $this->sendMiniCustom($resp);
				if($sessionfrom['type'] == 'ad' || $sessionfrom['type'] == 'ad_new' || $sessionfrom['type'] == 'hotel'){
				}else{
				sleep(1);
				    $text = "👆 点击上面的链接购买";
				    $resp = $this->respCustomText($text);
				    $res = $this->sendMiniCustom($resp);
				}
			}elseif($msg['adtype'] == 9){
				if($msg['mall_type'] == 'jd'){
					$api_url = str_replace("[apikey]",$settings['mall_myxq_apikey'],$msg['link_url']);
					$api_url = str_replace("[page]",$page,$api_url);
					$api_url = str_replace("[pagesize]",$pagesize,$api_url);
					$api_url = str_replace("[positionid]",$user['uid'],$api_url);
					$jd = json_decode(file_get_contents($api_url),true);
					if($jd['status_code'] == 200){
						$msg['link_url'] = $jd['data'];
					}
				}elseif($msg['mall_type'] == 'pdd'){
				}elseif($msg['mall_type'] == 'wph'){
				}elseif($msg['mall_type'] == 'tb'){
				}

                $thumb = str_replace("/addons/".$this->modulename,"",tomedia($msg['link_thumb']));
				$resp = $this->respCustomLink($msg['link_title'],$msg['link_desc'],$msg['link_url'],$thumb);
				$res = $this->sendMiniCustom($resp);
				if($sessionfrom['type'] == 'ad' || $sessionfrom['type'] == 'ad_new' || $sessionfrom['type'] == 'hotel'){
				}else{
				sleep(1);
				    $text = "👆 点击上面的链接购买";
				    $resp = $this->respCustomText($text);
				    $res = $this->sendMiniCustom($resp);
				}
			}elseif($msg['adtype'] == 15){
				$thumb = str_replace("/addons/".$this->modulename,"",tomedia($msg['link_thumb']));
				$resp = $this->respCustomLink($msg['link_title'],$msg['link_desc'],$msgtype['link_url'],$thumb);
				$res = $this->sendMiniCustom($resp);
			}else{
			}
		}
	}
	protected function respCustomText($content)
	{
		$data = array("touser" => $this->message["FromUserName"], "msgtype" => "text", "text" => array("content" => $content));
		return $data;
	}
	protected function respCustomImage($media_id)
	{
		$data = array("touser" => $this->message["FromUserName"], "msgtype" => "image", "image" => array("media_id" => $media_id));
		return $data;
	}
	protected function respCustomLink($title,$description,$url,$thumb_url)
	{
		$data = array("touser" => $this->message["FromUserName"], "msgtype" => "link", "link" => array("title" => $title,"description" => $description,"url" => $url,"thumb_url" => $thumb_url));
		return $data;
	}
	protected function sendMiniCustom($data, $acc = null)
	{
		$send = false;
		if (!empty($data) && $data["msgtype"] == "text") {
			$data["text"]["content"] = $this->procEmojiMsg($data["text"]["content"]);
		}
		if (empty($acc)) {
			if (empty($this->{"MimiAccount"})) {
				$acid = $this->TranAcId;
				$this->MimiAccount = WeAccount::createByUniacid($acid);
			}
			$acc = $this->MimiAccount;
		}
		if (!empty($acc)) {
			$token = $acc->getAccessToken();
			if (is_error($token) || empty($token)) {
				if (method_exists($acc, "clearAccessToken")) {
					$acc->clearAccessToken();
				} else {
					cache_delete("accesstoken:{$acc->account["key"]}");
				}
				$token = $acc->getAccessToken();
			}
			if (!empty($token) && is_string($token)) {
				$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
				$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
				$response = ihttp_request($url, $json);
				$send = $response["status"] == "OK";
				if (!empty($response["content"])) {
					$res = json_decode($response["content"], true);
					if (!empty($res["errcode"])) {
						$send = error($res["errcode"], $res["errmsg"]);
						$this->logging("发送错误", $json . "\n" . $response["content"]);
						if ($res["errcode"] == "41001") {
							if (method_exists($acc, "clearAccessToken")) {
								$acc->clearAccessToken();
							} else {
								cache_delete("accesstoken:{$acc->account["key"]}");
							}
						}
					}
				}
			} else {
				$send = error(-1, "无效token");
			}
		}
		return $send;
	}
	protected function mediaUpload($uniacid, $filename)
	{
		$media_id = false;
		$acc = WeAccount::createByUniacid($uniacid);
		$token = $acc->getAccessToken();
		if (!is_error($token)) {
			$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$token}&type=image";
			$data = array("media" => "@" . $filename);
			$response = ihttp_request($url, $data);
			$result = @json_decode($response["content"], true);
			if (!empty($result["media_id"])) {
				$media_id = $result["media_id"];
			}
		}
		return $media_id;
	}
	protected function procEmojiMsg($content)
	{
		if (preg_match("|\\\\u\\w{4}|", $content)) {
			$content = preg_replace_callback("#\\\\u([0-9a-f]+)#i", function ($str) {
				return utf8_bytes(hexdec($str[1]));
			}, $content);
			$content = urlencode($content);
		}
		if (preg_match_all('/\\\\[U\\\\+(\\\\w{4,})\\\\]/i', $content, $matchArray)) {
			if (!empty($matchArray[1])) {
				foreach ($matchArray[1] as $emojiUSB) {
					$content = str_ireplace("[U+{$emojiUSB}]", utf8_bytes(hexdec($emojiUSB)), $content);
				}
			}
		}
		return $content;
	}
}